<template>
  <div class="container">
    <base-title base-title="页面权限" />
    <div class="mgb20">
      <span class="label">角色：</span>
      <el-select v-model="role" @change="handleChange">
        <el-option v-for="item in permissStore.roleList" :key="item.id" :label="item.role_name" :value="item.id"> </el-option>
      </el-select>
    </div>
    <div class="mgb20 tree-wrapper">
      <el-tree ref="tree" :data="permissStore.permissionList" node-key="id" default-expand-all show-checkbox />
    </div>
    <el-button type="primary" @click="onSubmit">保存权限</el-button>
  </div>
</template>

<script setup lang="ts" name="permission">
  import { ref } from 'vue'
  import { ElTree } from 'element-plus'
  import { usePermissStore } from '../../store/permiss'
  import { queryRightsByRoleIdRequest, updateRoleRightsRequest } from '@/network/api/rights-api'
  import notification from '@/utils/notification'
  const role = ref<number>()
  const permissStore = usePermissStore()
  permissStore.permissionPageInit()

  // 保存权限
  const tree = ref<InstanceType<typeof ElTree>>()
  const onSubmit = async () => {
    if (!role.value) return notification.warning('请先选择角色~')
    // 获取选中的权限
    const newPermissArr: any[] = tree.value!.getCheckedKeys(true)
    const result = await updateRoleRightsRequest(role.value, newPermissArr)
    notification.success(result.msg)
  }

  // 切换角色
  const handleChange = async (val: string[]) => {
    const result = await queryRightsByRoleIdRequest(role.value)
    const keys = <any>[]
    result.result.forEach((item: any) => {
      keys.push(item.id)
      if (item.subs) {
        item.subs.forEach((i: any) => {
          keys.push(i.id)
        })
      }
    })
    // 更换选中节点
    tree.value!.setCheckedKeys(keys)
  }
</script>

<style scoped>
  .tree-wrapper {
    max-width: 500px;
  }
  .label {
    font-size: 14px;
  }
</style>
